package com.study.transaction.order.service;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author: chenhs
 * @date: Created in 10:52 2019/12/17
 **/
@Service
public class MQService {

    private static final Logger logger = LoggerFactory.getLogger(MQService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @PostConstruct
    public void setup() {
        /**
         * todo 不同的客户端 不同的写法----不用纠结
         * 消息发送完毕后，则回调此方法 ack代表是否成功
         */
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                // ack为true，代表MQ已经准确收到消息
                System.out.println("收到回执：" + correlationData);
                if (!ack) {
                    return;
                }

                try {
                    String sql = "update table_distributed_message set msg_status = 1 where unique_id = ?";
                    int count = jdbcTemplate.update(sql, correlationData.getId());

                    if (count != 1) {
                        logger.warn("警告：本地消息表的状态修改不成功");
                    }
                } catch (Exception e) {
                    logger.warn("警告：修改本地消息表的状态时出现异常", e);
                }
            }
        });
    }


    /**
     * 发送MQ消息，修改本地消息表的状态
     *
     * @param orderInfo
     */
    public void sendMsg(JSONObject orderInfo) {

        //1、发送消息到MQ -- 网络问题，MQ问题。。。没有成功发送
        // CorrelationData 当收到消息回执时，会附带上这个参数
        rabbitTemplate.convertAndSend("", "orderQueue", orderInfo.toJSONString()
                , new CorrelationData(orderInfo.getString("orderId")));
    }

}
